package cn.com.dhcc.ddi.task.service.transform;

import org.apache.commons.beanutils.ConvertUtils;

import java.lang.reflect.Method;
import java.lang.reflect.TypeVariable;
import java.util.HashMap;
import java.util.Map;

/**
 * 反射调用函数
 * @日期：2016/11/24 15:39
 * @作者：张洪涛
 * @版权所有：东华软件
 * @版本：1.0
 */
public class FxIvoke {
    /**
     * 调用函数
     * @param className class，完整包路径
     * @param methodName 函数名
     * @param args 参数数组
     * @return
     */
    public static Object call(String className,String methodName,String[] args) throws Exception {
            Class<?> clz = Class.forName(className);
            Object o = clz.newInstance();
            Map<String,Method> methodMap = getMethods(clz);
            Method method = methodMap.get(methodName);
            Class<?>[] parameterTypes = method.getParameterTypes();
            Object[] obj = new Object[args.length];
            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> clas = parameterTypes[i];
                obj[i] = ConvertUtils.convert(args[i], clas);

            }
            return method.invoke(o, obj);
    }
    /**
     * 获取定义方法
     * @param clazz
     * @return
     */
    public static Map<String,Method> getMethods(Class clazz){
        Map<String,Method> methodMap = new HashMap<String,Method>();
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            String methodName = method.getName();
            methodMap.put(methodName, method);
        }
        return methodMap;
    }

    private static void getMethodInfo(String className) throws ClassNotFoundException {
            Class clazz = Class.forName(className);
            Map<String,Method> methodMap = new HashMap<String,Method>();
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                String methodName = method.getName();
                methodMap.put(methodName, method);
                System.out.println("方法名称:" + methodName);
                Class<?>[] parameterTypes = method.getParameterTypes();
                for (Class<?> clas : parameterTypes) {
                    String parameterName = clas.getName();
                    System.out.println("参数名称:" + parameterName);
                }
            }
    }

    public static void main(String[] args) {
        String className = "cn.com.dhcc.ddi.task.service.transform.FXAction";
        String fxName = "replaceSuffix";
        String str = "gw_z_exch_t";
        String oldStr = "_exch_t";
        String newStr = "_t";
        String[] arg = new String[] {str, oldStr,newStr};
        try {
//            FxIvoke.getMethodInfo(className);
            System.out.println(FxIvoke.call(className,fxName,arg));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
